import { useCallback, useEffect, useRef, useState } from "react";
import http from "../http";
import styles from "./editor.module.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Button, Toast, Tooltip } from "@douyinfe/semi-ui";
import { IconEdit, IconEyeOpened, IconLockStroked } from "@douyinfe/semi-icons";
import Encrypted from "./encrypted";
import ReadonlyContainer from "./readonlyContainer";
import { useSettingStore } from "../store";
function EditorWang({ path }: { path: string }) {
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState<string>();
  const originalImages = useRef<string[]>([]);
  const toolbarConfig: Partial<IToolbarConfig> = {};
  const isFirstTime = useRef(true);
  const [mode, setMode] = useState<"editor" | "enctypt" | "readonly">(
    "readonly"
  );
  const { update } = useSettingStore();

  const updateOriginalImages = () => {
    // 更新originalImages为当前图片
    if (editor) {
      const images: any[] = editor.getElemsByType("image");
      originalImages.current = images.map((x) => x.src);
    }
  };

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入内容...",
    MENU_CONF: {
      uploadImage: {
        server: "http://localhost:10086/api/upload",
        fieldName: "image",
        maxFileSize: 10 * 1024 * 1024, // 10M
        allowedFileTypes: ["image/*"],
        timeout: 5 * 1000,
        onSuccess() {},
        onFailed(file: File, res: any) {
          console.log(`${file.name} 上传失败`, res);
        },
        customInsert(res: any, insertFn: any) {
          insertFn(res.data, "", res.data);
        },
      },
    },
  };

  // 保存文件内容
  const saveFile = useCallback(
    (content: string) => {
      if (editor) {
        const images: any[] = editor.getElemsByType("image");
        for (let index = 0; index < originalImages.current.length; index++) {
          const originalImage = originalImages.current[index];
          if (!images.find((z) => z.src == originalImage)) {
            http.delete(
              "/image?path=" +
                originalImage.substring(originalImage.lastIndexOf("/") + 1)
            );
          }
        }
      }

      http
        .postForm("/file?path=" + path, {
          content: content,
        })
        .then(() => {
          Toast.success("保存成功");
          update!({
            lastModTime: new Date().getUTCMilliseconds(),
          });
          updateOriginalImages();
        });
    },
    [editor, originalImages, path, update]
  );
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if ((event.ctrlKey || event.metaKey) && event.key === "s") {
        event.preventDefault();
        if (editor) {
          const text = editor.getHtml();
          saveFile(text);
        }
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);

      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor, saveFile]);
  useEffect(() => {
    isFirstTime.current = true;
    getFile(path);
  }, [path]);

  const getFile = useCallback(
    (path: string) => {
      if (path) {
        http.get("/file?path=" + path).then((x: any) => {
          if (x.success) {
            if (x.data.isEncrypt) {
              setMode("enctypt");
            } else {
              setContent(x.data.content);
              if (x.data.content == "") {
                setMode("editor");
              } else {
                setMode("readonly");
              }
            }
          }
        });
      }
    },
    [path]
  );

  const setContent = (content: string) => {
    setHtml(content);
  };

  useEffect(() => {
    if (isFirstTime.current && editor) {
      const images: any[] = editor.getElemsByType("image");
      originalImages.current = images.map((x) => x.src);
    }
    // if (html && html.length > 0 && !html.startsWith("<")) {
    //   setMode("enctypt");
    // }
  }, [html, editor]);
  const onConfirmEncrypt = () => {
    http.post("/encrypt?path=" + path).then((x: any) => {
      if (x.success) {
        console.log(x);
        getFile(path);
      }
    });
  };
  const onConfirmDecrypt = () => {
    http.post("/decrypt?path=" + path).then((x: any) => {
      if (x.success) {
        console.log(x);
        getFile(path);
      }
    });
  };
  function onEditorChange(): void {
    update!({
      currentPath: path,
    });
  }

  return (
    <div id="editor" className={styles["editor-wrapper"]}>
      {path && (
        <>
          {mode == "editor" ? (
            <>
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: "1px solid #ccc", zIndex: "200" }}
                className={styles["editor-toolbar"]}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={onEditorChange}
                mode="default"
                style={{ overflowY: "hidden", paddingTop: "40px" }}
                className="h-full"
              />
            </>
          ) : mode == "enctypt" ? (
            <Encrypted onClickDecrypt={onConfirmDecrypt}></Encrypted>
          ) : (
            <ReadonlyContainer path={path} html={html}></ReadonlyContainer>
          )}

          <div className={styles["float-btns"]}>
            {(mode == "editor" || mode == "readonly") && (
              <Tooltip content={"加密文件"} position={"left"}>
                <Button
                  className={styles["float-btn"]}
                  size={"large"}
                  type="primary"
                  icon={
                    <IconLockStroked
                      size={"large"}
                      onClick={onConfirmEncrypt}
                    />
                  }
                />
              </Tooltip>
            )}
            {mode == "editor" && (
              <Tooltip content={"只读模式"} position={"left"}>
                <Button
                  className={styles["float-btn"]}
                  size={"large"}
                  type="primary"
                  icon={
                    <IconEyeOpened
                      size={"large"}
                      onClick={() => setMode("readonly")}
                    />
                  }
                />
              </Tooltip>
            )}
            {mode == "readonly" && (
              <Tooltip content={"编辑模式"} position={"left"}>
                <Button
                  className={styles["float-btn"]}
                  size={"large"}
                  type="primary"
                  icon={<IconEdit size={"large"} />}
                  onClick={() => setMode("editor")}
                />
              </Tooltip>
            )}
          </div>
        </>
      )}
    </div>
  );
}
export default EditorWang;
